package com.staryy.activiti7_workflow.controller;

import com.staryy.activiti7_workflow.util.AjaxResponse;
import com.staryy.activiti7_workflow.util.GlobalConfig;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;


/**
 * 流程定义接口
 */
@RestController
@RequestMapping("/processDefinition")
public class ProcessDefinitionController {

    @Autowired
    private RepositoryService repositoryService;

    /**
     * 通过上传BPMN文件，添加流程定义
     *
     * @return
     */
    @PostMapping("/uploadStreamAndDeployment")
    @ResponseBody
    public AjaxResponse uploadStreamAndDeployment(@RequestParam("processFile") MultipartFile file,
                                                  @RequestParam("processName") String processName) {
        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 获取文件后缀
            String extension = FilenameUtils.getExtension(fileName);
            // 获取文件字节流对象
            InputStream inputStream = file.getInputStream();
            Deployment deployment = null;
            if ("zip".equals(extension)) {
                ZipInputStream zipInputStream = new ZipInputStream(inputStream);
                deployment = repositoryService.createDeployment()
                        .addZipInputStream(zipInputStream)
                        .name(processName)
                        .deploy();
            } else {
                deployment = repositoryService.createDeployment()
                        .addInputStream(fileName, inputStream)
                        .name(processName)
                        .deploy();
            }

            return AjaxResponse.AjaxData(GlobalConfig.ResponseCode.SUCCESS.getCode(),
                    GlobalConfig.ResponseCode.SUCCESS.getDesc(), deployment.getId() + ";" + fileName);
        } catch (Exception e) {
            return AjaxResponse.AjaxData(GlobalConfig.ResponseCode.ERRPR.getCode(),
                    "BPMN文件上传失败", e.toString());
        }
    }

    /**
     * 部署BPMN字符
     *
     * @return
     */
    @PostMapping("/addDeploymentByString")
    @ResponseBody
    public AjaxResponse addDeploymentByString(@RequestParam("stringBPMN") String stringBPMN,
                                              @RequestParam("deploymentName") String deploymentName) {
        try {
            Deployment deployment = repositoryService.createDeployment()
                    .addString("CreateWithBPMNJS.bpmn", stringBPMN)
                    .name(deploymentName)
                    .deploy();
            return AjaxResponse.AjaxData(GlobalConfig.ResponseCode.SUCCESS.getCode(),
                    GlobalConfig.ResponseCode.SUCCESS.getDesc(), deployment.getId());
        } catch (Exception e) {
            return AjaxResponse.AjaxData(GlobalConfig.ResponseCode.ERRPR.getCode(),
                    "string部署流程失败", e.toString());
        }
    }


    /**
     * 获取流程定义列表
     *
     * @return
     */
    @GetMapping("/getDefinitions")
    @ResponseBody
    public AjaxResponse getDefinitions() {
        List<Map<String, Object>> mapList = new ArrayList<>();
        List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().list();
        for (ProcessDefinition definition : list) {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("name", definition.getName());
            dataMap.put("key", definition.getKey());
            dataMap.put("resourceName", definition.getResourceName());
            dataMap.put("deploymentId", definition.getDeploymentId());
            dataMap.put("version", definition.getVersion());
            mapList.add(dataMap);
        }
        return AjaxResponse.AjaxData(GlobalConfig.ResponseCode.SUCCESS.getCode(), GlobalConfig.ResponseCode.SUCCESS.getDesc(), mapList);
    }


    /**
     * 获取流程定义XML
     *
     * @return
     */
    @GetMapping("/getDefinitionXml")
    public void getDefinitionXml(HttpServletResponse response,
                                 @RequestParam("deploymentId") String deploymentId,
                                 @RequestParam("resourceName") String resourceName) {
        try {

            InputStream inputStream = repositoryService.getResourceAsStream(deploymentId, resourceName);
            int count = inputStream.available();
            byte[] bytes = new byte[count];
            response.setContentType("text/xml");
            ServletOutputStream outputStream = response.getOutputStream();
            while (inputStream.read(bytes) != -1) {
                outputStream.write(bytes);
            }
            inputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 删除流程部署，删除流程定义
     *
     * @return
     */
    @GetMapping("/delDefinition")
    @ResponseBody
    public AjaxResponse delDefinition(
            @RequestParam("pdID") String pdID) {
        try {
            repositoryService.deleteDeployment(pdID,true);
            return AjaxResponse.AjaxData(GlobalConfig.ResponseCode.SUCCESS.getCode(),
                    GlobalConfig.ResponseCode.SUCCESS.getDesc(), null);
        } catch (Exception e) {
            return AjaxResponse.AjaxData(GlobalConfig.ResponseCode.ERRPR.getCode(),
                    "流程部署删除失败", e.toString());
        }
    }


}
